import router from "@/router";
import { uni_router } from "@/router/utils";
import type { NextOptions } from "@/router/utils";
import qs from "qs";
import { useAccountStore } from "@/store/use-account";

/**
 * @description 基础路由跳转函数，用于处理页面跳转前的逻辑判断（如登录状态、路由守卫等）
 * @param route - 跳转目标路由配置对象
 * */
export const basic = (route: NextOptions) => {
    const accountStore = useAccountStore();

    // 获取当前页面栈信息
    const current = getCurrentPages();

    /**
     * @description 查询是否有特殊配置的路由
     * */
    const target = router.routes.find((o) => {
        const currentUrl = current[0].route;

        let url = route.url.replace(/\?.*$/, "");

        if (!url.startsWith("/")) {
            url = `/${currentUrl}/${url}`;
        }

        return o.path === url;
    });

    /**
     * @description 如果目标页面没有特殊配置 直接跳转
     * */
    if (typeof router.routes !== "object" || router.routes.length <= 0 || !target) {
        return next(route);
    }

    /**
     * @description 继续执行路由跳转逻辑，根据规则判断是否需要登录
     * @param route - 跳转目标路由配置对象
     * @param rules - 跳转方式规则，"next"表示使用next方法，其他值表示使用push方法
     * */
    const continueRoute = (route: NextOptions, rules = "next") => {
        /**
         * @description 需要登录状态才能进入
         * */
        if (target.isNeedLogin && !accountStore.isLogin) {
            const params = {
                from: route.url
            };
            next({
                url: `${router.PATH.__PACKAGE_LOGIN}?${qs.stringify(params)}`,
                jumpType: "NavigateTo"
            });
        } else {
            return rules === "next" ? next(route) : push(route);
        }
    };

    // 判断是否存在路由前置守卫
    if (target.beforeEnter) {
        target.beforeEnter({
            next: (r?: NextOptions) => {
                /**
                 * @description 执行路由守卫中的next回调，根据参数决定跳转方式
                 * @param r - 可选的路由配置对象，若未提供则使用原route参数
                 * */
                continueRoute(r ?? route, typeof r === "undefined" ? "next" : "push");
            },
            to: route,
            from: { url: `/${current[0].route}` }
        });
    } else {
        continueRoute(route);
    }
};

/**
 * @description 根据jumpType执行具体的页面跳转操作
 * @param route - 跳转目标路由配置对象
 * */
export const next = async (route: NextOptions) => {
    if (route.jumpType) {
        switch (route.jumpType) {
            case "NavigateTo":
                await uni_router.navigateTo(route);
                break;
            case "RedirectTo":
                await uni_router.redirectTo(route);
                break;
            case "SwitchTab":
                await uni_router.switchTab(route);
                break;
            case "ReLaunch":
                await uni_router.reLaunch(route);
                break;
            default:
                await uni_router.navigateTo(route);
                break;
        }
    } else {
        await uni_router.navigateTo(route);
    }
};

/**
 * @description 使用navigateTo方式跳转到指定页面
 * @param route - 跳转目标路由配置对象
 * */
export const push = (route: NextOptions) => {
    route.jumpType = "NavigateTo";
    basic(route);
};

/**
 * @description 使用redirectTo方式跳转到指定页面
 * @param route - 跳转目标路由配置对象
 * */
export const redirectTo = (route: NextOptions) => {
    route.jumpType = "RedirectTo";
    basic(route);
};

/**
 * @description 使用redirectTo方式跳转到指定页面
 * @param route - 跳转目标路由配置对象
 * */
export const reLaunch = (route: NextOptions) => {
    route.jumpType = "ReLaunch";
    basic(route);
};

/**
 * @description 使用switchTab方式跳转到指定tab页面
 * @param route - 跳转目标路由配置对象
 * */
export const switchTab = (route: NextOptions) => {
    route.jumpType = "SwitchTab";
    basic(route);
};
